<?php

namespace App\Http\Controllers\applet_api;

use App\Http\Controllers\Controller;
use App\Models\InteractionType;
use Illuminate\Http\Request;

class InteractionTypeController extends Controller
{

    public function index(Request $Request)
    {
        $search = $Request->search;
        $sql = InteractionType::orderBy('id','asc')
                ->when($search, function ($query, $search) {
                    return $query->where('name','like', $search.'%');
                });
        $total = $sql->count();
        $data = $sql->get();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data,'total'=>$total]);
    }

    public function update(Request $Request)
    {
        if(!$Request->name){
            return response()->json(['code' => '403', 'msg' => '请输入分类名称']);
        }

        if(!$Request->id){
            $is = InteractionType::where('name',$Request->name)->first();
            if($is){
                return response()->json(['code' => '403', 'msg' => '该分类已存在']);
            }
            $data = new InteractionType();
            $data->create_time = time();
        }else{
            $is = InteractionType::where('name',$Request->name)->where('id','<>',$Request->id)->first();
            if($is){
                return response()->json(['code' => '403', 'msg' => '该分类已存在']);
            }

            $data = InteractionType::find($Request->id);
        }

        $data->name = $Request->name;
        $data->update_time = time();
        $data->save();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function delete(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '403', 'msg' => '请选择要删除的记录']);
        }
        $data = InteractionType::find($Request->id);
        if(!$data){
            return response()->json(['code' => '403', 'msg' => '记录不存在']);
        }
        $data->delete();
        return response()->json(['code' => '200', 'msg' => 'success']);
    }
}
